package com.boil.qz.safekavass.service;

import com.boil.qz.safekavass.dao.MybatisDao;
import com.boil.qz.safekavass.model.LoginUser;
import com.boil.qz.safekavass.model.Notice;
import com.boil.qz.safekavass.pojo.NoticeVo;
import com.boil.qz.safekavass.repository.NoticeRepository;
import com.boil.qz.safekavass.web.request.param.AddNoticeParam;
import com.boil.util.Constants;
import com.boil.util.DateUtils;
import com.boil.util.Page;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by ChenYong on 2017-04-17.
 * <br>
 * 通知 Service。
 */
@Service
public class NoticeService extends JpaRepositoryService<Notice, Long> {
    /**
     * 注入 Mybatis Dao
     */
    @Autowired
    private MybatisDao mybatisDao;
    /**
     * 注入通知实体仓库
     */
    @Autowired
    private NoticeRepository noticeRepository;
    /**
     * 注入登录用户 Service
     */
    @Autowired
    private LoginUserService loginUserService;

    /**
     * 分页查询通知。
     *
     * @param page 分页实例
     */
    public void findInPage(Page<NoticeVo> page) {
        mybatisDao.selectInPage("noticeVoNs.findInPage", page);
    }

    /**
     * 根据通知 ID 查询通知。
     *
     * @param id 通知 ID
     * @return 通知实例
     */
    public Notice findById(long id) {
        Notice notice = findOne(id);

        // 美化内容
        notice.setNoticeContent(notice.getNoticeContent()
                .replaceAll(Constants.CONTENT_NEWLINE_RN_RE, Constants.CONTENT_NEWLINE_BR_SPAN)
                .replaceAll(Constants.CONTENT_NEWLINE_N_RE, Constants.CONTENT_NEWLINE_BR_SPAN)
                .replaceAll(Constants.CONTENT_NEWLINE_BR_SPAN_RE, Constants.CONTENT_NEWLINE_BR_SPAN)
                .replaceAll(Constants.CONTENT_NEWLINE_SHIT_RE, Constants.EMPTY_STR));

        return notice;
    }

    /**
     * 保存通知。
     *
     * @param param 添加通知的请求参数
     */
    public void save(AddNoticeParam param) {
        // 获取登录用户的操作信息
        Subject subject = SecurityUtils.getSubject();
        // 获取登录用户的 Session
        Session session = subject.getSession();
        // 获取登录用户
        LoginUser loginUser = (LoginUser) session.getAttribute(Constants.LOGIN_USER);

        // 查询用户
        LoginUser loginUser1 = loginUserService.findOne(loginUser.getId());
        // 创建通知实例
        Notice notice = new Notice();

        BeanUtils.copyProperties(param, notice);

        notice.setLoginUser(loginUser1);
        notice.setNoticeFiles(param.getNoticeFilePaths());
        notice.setNoticeFilesName(param.getNoticeFileNames());
        notice.setNoticeCreateTime(DateUtils.getCurrDateStr(Constants.DATE_TIME_FORMAT_1));
        notice.setNoticeCreatePerson(loginUser1.getLoginName());

        save(notice);
    }
}